using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;

namespace Circa.Protocol.Irc {

    public class IrcMessage {

        public string Raw { get; set; }
        public string OriginName { get; set; }
        public string TargetName { get; set; }

        public Server Server { get; set; }
        public ITargetable Origin { get; set; }
        public ITargetable Target { get; set; }
        public string Verb { get; set; }
        public List<string> Args { get; set; }

        private List<string> _args = new List<string>( );

        private IrcMessage( ) { }

        public IrcMessage( string line ) {
            Raw = line;
            ParseLine( line );
        }

        protected void ParseLine( string line ) {
            char[] Delimiters = new char[] { ' ' };

            if ( line[ 0 ] == ':' ) {
                int len = line.IndexOf( ' ', 1 );
                if ( len > -1 ) {
                    OriginName = line.Substring( 1, len - 1 );
                    line = line.Remove( 0, len + 1 );
                }
            }

            string[] pieces = line.Split( Delimiters, 2, StringSplitOptions.RemoveEmptyEntries );
            if ( pieces.Length < 1 )
                return;
            Verb = pieces[ 0 ];
            if ( pieces.Length < 2 )
                return;
            if ( pieces[ 1 ][ 0 ] == ':' ) {
                Args.Add( pieces[ 1 ].Substring( 1 ) );
                return;
            }

            pieces = pieces[ 1 ].Split( Delimiters, 2, StringSplitOptions.RemoveEmptyEntries );
            if ( pieces.Length < 1 )
                return;
            TargetName = pieces[ 0 ];
            if ( pieces.Length < 2 )
                return;
            if ( pieces[ 1 ][ 0 ] == ':' ) {
                Args.Add( pieces[ 1 ].Substring( 1 ) );
                return;
            }

            pieces = pieces[ 1 ].Split( Delimiters, 15, StringSplitOptions.None );
            for ( int n = 0; n < pieces.Length; n++ ) {
                if ( pieces[ n ][ 0 ] == ':' ) {
                    Args.Add( string.Join( " ", pieces, n, pieces.Length - n ).Substring( 1 ) );
                    break;
                }
                Args.Add( pieces[ n ] );
            }
        }

    }

}
